import {Component, OnInit} from '@angular/core';
import {BarnMenu} from "../entity/barn-menu";
import {BarnMenuService} from "../service/barn-menu.service";
import {NzMessageService} from "ng-zorro-antd/message";

@Component({
  selector: 'app-menu-info',
  templateUrl: './menu-info.component.html',
  styleUrls: ['./menu-info.component.less']
})
export class MenuInfoComponent implements OnInit {

  loading = false
  menus: BarnMenu[]
  // 所有menu Map
  menuMap: { [pid: string]: BarnMenu }

  constructor(private menuService: BarnMenuService, private msg: NzMessageService) {
  }

  ngOnInit(): void {
    this.search()
  }

  search() {
    this.loading = true;
    this.menuService.getAll()
      .subscribe(value => {
        this.menuListToMap(value);
        this.loading = false
      }, () => this.loading = false)
  }

  menuListToMap(menuList: BarnMenu[] = []) {
    if (!menuList.length) {
      return {}
    }
    const menuMap: { [pid: string]: BarnMenu } = {};
    const topMenuArray: BarnMenu[] = [];
    for (let i = 0; i < menuList.length; i++) {
      menuList[i].expand = true
      menuMap[menuList[i].pid] = menuList[i];
      if (!menuList[i].parentId) {
        topMenuArray.push(menuList[i])
      }
    }

    // 构造层级关系
    for (let i = 0; i < menuList.length; i++) {
      if (menuList[i].parentId) {
        const parent = menuMap[menuList[i].parentId];
        if (parent) {
          if (!parent.children) {
            parent.children = [];
          }
          parent.children.push(menuList[i])
        } else {
          menuList[i].parentId = null
        }
      }
    }
    this.menuMap = menuMap

    //构造一个树顺序的array,按父子关系排序，就是树全展开的样子
    let result: BarnMenu[] = []
    for (let i = 0; i < topMenuArray.length; i++) {
      topMenuArray[i].level = 0
      result.push(topMenuArray[i]);
      result = result.concat(this.getAllChildren(topMenuArray[i], 1));
    }
    this.menus = result;
  }

  getAllChildren(parent: BarnMenu, level: number): BarnMenu[] {
    if (!parent.children || !parent.children.length) {
      return []
    }
    const children = parent.children;
    let result: BarnMenu[] = []
    for (let i = 0; i < children.length; i++) {
      children[i].level = level
      result.push(children[i])
      result = result.concat(this.getAllChildren(children[i], (level + 1)))
    }
    return result
  }

  delete(pid: string) {
    this.loading = true
    this.menuService.deleteById(pid)
      .subscribe(value => {
        this.loading = false
        this.msg.success("删除成功")
        this.search()
      }, () => this.loading = false)

  }

  isShow(menu: BarnMenu): boolean {
    // 父亲，爷爷，爷爷的爸爸...,是不是展开
    if (!menu.parentId) {
      return true
    } else {
      const parent = this.menuMap[menu.parentId];
      if (parent) {
        if (!parent.expand) {
          return false
        } else {
          return this.isShow(parent)
        }
      } else {
        return true
      }
    }
  }
}
